package com.thinkgem.jeesite.modules.wechat.utils;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.wechat.entity.WechatApiToken;
import com.xiaoleilu.hutool.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class TokenUtils extends Global{
	
	public final static long TIME_OUT = 7000;	// 超时为7200秒
	
	private static Map<String , WechatApiToken> tokenMap  = new HashMap<String, WechatApiToken>();

	private static Logger logger = LoggerFactory.getLogger(TokenUtils.class);

	/**
	 * 获取token
	 * @return
	 */
	public static String getAPIToken(){
		WechatApiToken token = tokenMap.get(appId);
		if(isValiable(token)){
			logger.info("当前Token可用未超时.");
			return token.getToken();
		}else{
			String strToken = getNewToken(appId,secret);
			return strToken;
		}
	}
	
	
	/**
	 * @author Jakemanse
	 * @time 2014-6-21  下午5:17:14
	 * @function <p>当前的Token是否可用是否超时  </p>
	 * @param token
	 * @return
	 */
	private static boolean isValiable(WechatApiToken token){
		if(token == null) return false;
		long now = System.currentTimeMillis();
		long diff = now - token.getStart() ;
		if(diff/1000 > TIME_OUT){
			return false;
		}
		return true;
	}
	
	/**
	 * @author Jakemanse
	 * @time 2014-6-21  下午5:16:59
	 * @function <p> 重新获取一个新Token </p>
	 * @return
	 */
	private static String getNewToken(String appId,String secret){
		HashMap<String, Object> paramMap = new HashMap<>();
		paramMap.put("grant_type", "client_credential");
		paramMap.put("appid", appId);
		paramMap.put("secret", secret);
		String json = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token", paramMap);
		logger.info(json);
		//token json 解析
		Map<String,String> map = (Map<String, String>) JsonMapper.fromJsonString(json, HashMap.class);
		String accessToken = map.get("access_token");
		if(StringUtils.isNotEmpty(accessToken)){
			WechatApiToken  apiToken = new WechatApiToken();
			apiToken.setAppId(appId);
			apiToken.setStart(System.currentTimeMillis());
			apiToken.setSecretKey(secret);
			apiToken.setToken(accessToken);
			tokenMap.put(appId,apiToken);
			logger.info("获取新的token："+accessToken);
		}else{
			logger.info("获取token失败");
		}
		return accessToken;
	}

}
